//
//  LcButton.m
//  ExampleObjective-C
//
//  Created by weijieMac on 2017/2/27.
//  Copyright © 2017年 ouy.Aberi. All rights reserved.
//

#import "LcButton.h"

@interface HySpinerLayer : CAShapeLayer

- (instancetype)initWithFrame:(CGRect)frame;

- (void)beginAnimation;

- (void)stopAnimation;

@end

@implementation HySpinerLayer

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super init];
    if (self) {
        CGFloat radius = CGRectGetHeight(frame) / 4;
        CGRect lastFrame = CGRectZero;
        CGPoint center = CGPointZero;
        if (CGRectGetWidth(frame)>CGRectGetHeight(frame)) {//宽>高
            lastFrame = CGRectMake((CGRectGetWidth(frame)-CGRectGetHeight(frame))/2, 0, CGRectGetHeight(frame), CGRectGetHeight(frame));
            center = CGPointMake(CGRectGetHeight(frame) / 2, CGRectGetMidY(lastFrame));
        }else if (CGRectGetWidth(frame)<CGRectGetHeight(frame)) {//高>宽
            lastFrame = CGRectMake(0, (CGRectGetHeight(frame)-CGRectGetWidth(frame))/2, CGRectGetWidth(frame), CGRectGetWidth(frame));
            center = CGPointMake(CGRectGetWidth(frame) / 2, CGRectGetMidX(lastFrame));
        }else {//正方形
            lastFrame = CGRectMake(0, 0, CGRectGetHeight(frame), CGRectGetHeight(frame));
            center = CGPointMake(CGRectGetHeight(frame) / 2, CGRectGetMidY(lastFrame));
        }
        
        self.frame = lastFrame;
        
        CGFloat startAngle = 0 - M_PI_2;
        CGFloat endAngle = M_PI * 2 - M_PI_2;
        BOOL clockwise = true;
        self.path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:clockwise].CGPath;
        self.fillColor = nil;
        self.strokeColor = [UIColor whiteColor].CGColor;
        self.lineWidth = 1;
        
        self.strokeEnd = 0.4;
        self.hidden = true;
    }
    return self;
}

-(void)beginAnimation {
    self.hidden = false;
    CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotate.fromValue = 0;
    rotate.toValue = @(M_PI * 2);
    rotate.duration = 0.4;
    rotate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    rotate.repeatCount = HUGE;
    rotate.fillMode = kCAFillModeForwards;
    rotate.removedOnCompletion = false;
    [self addAnimation:rotate forKey:rotate.keyPath];
}

-(void)stopAnimation {
    self.hidden = true;
    [self removeAllAnimations];
}

@end
@interface YQButtonCircleSet : NSObject

@property CGFloat circleCenterX;
@property CGFloat circleCenterY;
@property CGFloat circleWidth;
@property CGFloat circleRait;

@end
@implementation YQButtonCircleSet

@end
@interface LcButton()<CAAnimationDelegate>
@property (nonatomic, strong) HySpinerLayer *spinerLayer;
@property(nonatomic,assign)int loopCount;

@property(nonatomic,strong)NSMutableDictionary *circles;

@property(nonatomic,assign)int circleFlag;

@end

@implementation LcButton
-(void)setAnimationDuration:(NSTimeInterval)AnimationDuration{
    _AnimationDuration = AnimationDuration;
    self.loopCount = self.AnimationDuration / 0.02;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.highlightedColor = RGBA(255, 255, 255, 0.7);
        
        self.AnimationDuration = 1;
        self.loopCount = self.AnimationDuration / 0.02;
        
        self.circles = [NSMutableDictionary dictionary];
        self.circleFlag = 0;
        self.originalBgColor = WHITECOLOR;
        [self addTarget:self action:@selector(touchedDown:event:) forControlEvents:UIControlEventTouchDown];
        [self addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
        return self;
     
        
    }
    return self;
}
// 当控件加载完成之前调用
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    
    self.highlightedColor = RGBA(255, 255, 255, 0.7);
    
    self.AnimationDuration = 1;
    self.loopCount = self.AnimationDuration / 0.02;
    
    self.circles = [NSMutableDictionary dictionary];
    self.circleFlag = 0;
     self.originalBgColor = WHITECOLOR;
    
    [self addTarget:self action:@selector(touchedDown:event:) forControlEvents:UIControlEventTouchDown];
    [self addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
    return self;
}
- (void)setOriginalBgColor:(UIColor *)originalBgColor
{
   
    _originalBgColor = originalBgColor;
}

- (void)btnClicked
{
    self.userInteractionEnabled = NO;
   
    [self setTitleColor:CLEARCOLOR forState:0];
    [self.layer addSublayer:self.spinerLayer];
    [self.spinerLayer beginAnimation];
    
}
- (void)stopAnimation
{
     [self setTitleColor:WHITECOLOR forState:0];
    [self.spinerLayer stopAnimation];
    [self.layer removeAllAnimations];
    self.userInteractionEnabled = YES;
}
-(void)drawRect:(CGRect)rect{
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGFloat endAngle = M_PI * 2;
    
    for (YQButtonCircleSet *circleSet in self.circles.allValues) {
        CGContextAddArc(context,
                        circleSet.circleCenterX,
                        circleSet.circleCenterY,
                        circleSet.circleWidth * circleSet.circleRait,
                        0,
                        endAngle,
                        NO);
        [[self.highlightedColor colorWithAlphaComponent:(1-circleSet.circleRait)] setStroke];
        [[self.highlightedColor colorWithAlphaComponent:(1-circleSet.circleRait)] setFill];
        
        CGContextFillPath(context);
    }
}
-(void)touchedDown:(UIButton *)btn event:(UIEvent *)event{
    
    UITouch *touch = event.allTouches.allObjects.firstObject;
    CGPoint touchePoint = [touch locationInView:btn];
    
    NSString *key = [NSString stringWithFormat:@"%d",self.circleFlag];
    YQButtonCircleSet *set = [YQButtonCircleSet new];
    set.circleCenterX = touchePoint.x;
    set.circleCenterY = touchePoint.y;
    set.circleRait = 0;
    
    CGFloat maxX = touchePoint.x>(self.frame.size.width-touchePoint.x)?touchePoint.x:(self.frame.size.width-touchePoint.x);
    CGFloat maxY = touchePoint.y>(self.frame.size.width-touchePoint.y)?touchePoint.y:(self.frame.size.height-touchePoint.y);
    set.circleWidth = maxX>maxY?maxX:maxY;
    
    [self.circles setObject:set forKey:key];
    
    NSTimer *timer = [NSTimer timerWithTimeInterval:0.01
                                             target:self
                                           selector:@selector(TimerFunction:)
                                           userInfo:@{@"key":key}
                                            repeats:YES];
    
    [NSRunLoop.mainRunLoop addTimer:timer forMode:NSRunLoopCommonModes];
    
    self.circleFlag++;
}

-(void)TimerFunction:(NSTimer *)timer{
    
    [self setNeedsDisplay];
    
    NSDictionary *userInfo = timer.userInfo;
    
    NSString *key = userInfo[@"key"];
    
    YQButtonCircleSet *set = self.circles[key];
    
    if(set.circleRait<=1){
        
        set.circleRait += (1.0/self.loopCount);
        
    }else{
        [self.circles removeObjectForKey:key];
        
        [timer invalidate];
    }
}


- (HySpinerLayer *)spinerLayer
{
    if (!_spinerLayer) {
        _spinerLayer = [[HySpinerLayer alloc] initWithFrame:self.frame];
        _spinerLayer.strokeColor = self.originalBgColor.CGColor;
    }
    return _spinerLayer;
}

@end


